from flask import Flask, request, jsonify
import logging
import csv
import os
import datetime
from score_calculator import calculate_score

app = Flask(__name__)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

CSV_FILE = 'webhook_data.csv'
SCORE_CSV_FILE = 'Member_Score.csv'

# 确保CSV文件存在并包含表头
def init_csv_file():
    if not os.path.exists(CSV_FILE):
        with open(CSV_FILE, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['部门', '姓名', '申请人', '申请时间', '数据ID','中稿媒体', '是否含图片、动图等素材', '投稿类别', '是否为头版', 
                           '配图数量', '是否多图', '图片数量', '稿件类型', '文字类稿费金额', 
                           '图片类稿费金额', '文章类型', '新闻类文章稿费金额', '通讯类文章稿费金额', 
                           '图片类文章稿费金额', '其他文学类稿费金额', '东烟视频网播出次数', 
                           '新华财经-视频播出次数', '成员', '链接', '标题'])

# 确保得分CSV文件存在并包含表头
def init_score_csv_file():
    if not os.path.exists(SCORE_CSV_FILE):
        with open(SCORE_CSV_FILE, 'w', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow(['成员', '部门', '中稿媒体', '标题', '得分', '链接', '时间'])

# 将webhook数据转换为score_calculator可处理的格式
def convert_data_for_scoring(data):
    scoring_data = {}
    
    # 设置平台
    scoring_data['platform'] = data.get('中稿媒体', '')
    
    # 处理是否含图片、动图等素材
    has_media = data.get('是否含图片、动图等素材', '') == '是'
    scoring_data['has_media'] = has_media
    
    # 处理东方烟草报的特殊字段
    if scoring_data['platform'] == '东方烟草报':
        # 设置文章类型 - 优先使用稿件类型，如果不存在则使用投稿类别
        article_type = data.get('稿件类型', '') or data.get('投稿类别', '')
        if article_type:
            scoring_data['article_type'] = article_type
        
        # 是否为头版
        is_front_page = data.get('是否为头版', '') == '是'
        scoring_data['is_front_page'] = is_front_page
        
        # 图片数量 - 依次尝试不同可能的字段名
        image_count_str = data.get('图片数量', '') or data.get('通讯类配图数量', '') or data.get('配图数量', '')
        if image_count_str and image_count_str.isdigit():
            scoring_data['image_count'] = int(image_count_str)
    
    # 处理浙江烟草杂志的特殊字段
    elif scoring_data['platform'] == '浙江烟草杂志':
        # 设置文章类型
        article_type = data.get('稿件类型', '')
        if article_type:
            scoring_data['article_type'] = article_type
        
        # 稿费金额
        fee_str = data.get('文字类稿费金额', '') or data.get('图片类稿费金额', '')
        if fee_str and fee_str.replace('.', '', 1).isdigit():
            scoring_data['fee'] = float(fee_str)
    
    # 处理《中烟报》的特殊字段
    elif scoring_data['platform'] == '《中烟报》':
        # 设置文章类型
        article_type = data.get('文章类型', '')
        if article_type:
            scoring_data['article_type'] = article_type
        
        # 稿费金额，根据不同类型获取
        fee_str = ''
        if article_type == '新闻类':
            fee_str = data.get('新闻类文章稿费金额', '')
        elif article_type == '通讯类':
            fee_str = data.get('通讯类文章稿费金额', '')
        elif article_type == '图片类':
            fee_str = data.get('图片类文章稿费金额', '')
        elif article_type == '其他文学类':
            fee_str = data.get('其他文学类稿费金额', '')
        
        if fee_str and fee_str.replace('.', '', 1).isdigit():
            scoring_data['fee'] = float(fee_str)
    
    return scoring_data

# 保存分数到CSV文件
def save_score_to_csv(member, department, platform, title, score, link):
    # 确保文件存在
    init_score_csv_file()
    
    # 获取当前时间
    current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # 处理可能存在多个成员的情况，以逗号分隔
    members = [m.strip() for m in member.split(',') if m.strip()]
    
    # 如果没有成员信息，仍然保存一条记录
    if not members:
        members = ['']
    
    # 为每个成员分别写入一行记录
    with open(SCORE_CSV_FILE, 'a', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        for single_member in members:
            writer.writerow([single_member, department, platform, title, score, link, current_time])
    
    # 记录日志
    if len(members) > 1:
        logger.info(f"成员信息已拆分，为 {len(members)} 名成员各创建一条记录: {', '.join(members)}")

@app.route('/webhook', methods=['POST'])
def webhook():
    """
    接收轻流Webhook请求并将数据存入CSV文件，同时计算分数并保存
    """
    try:
        # 获取JSON数据
        data = request.get_json()
        
        logger.info(f"Received webhook data: {data}")
        
        # 初始化CSV文件
        init_csv_file()
        
        # 写入CSV文件
        with open(CSV_FILE, 'a', newline='', encoding='utf-8') as f:
            writer = csv.writer(f)
            writer.writerow([
                data.get('部门', ''),
                data.get('姓名', ''),
                data.get('申请人', ''),
                data.get('申请时间', ''),
                data.get('数据ID', ''),
                data.get('中稿媒体', ''),
                data.get('是否含图片、动图等素材', ''),
                data.get('投稿类别', ''),
                data.get('是否为头版', ''),
                data.get('配图数量', ''),
                data.get('是否多图', ''),
                data.get('图片数量', ''),
                data.get('稿件类型', ''),
                data.get('文字类稿费金额', ''),
                data.get('图片类稿费金额', ''),
                data.get('文章类型', ''),
                data.get('新闻类文章稿费金额', ''),
                data.get('通讯类文章稿费金额', ''),
                data.get('图片类文章稿费金额', ''),
                data.get('其他文学类稿费金额', ''),
                data.get('东烟视频网播出次数', ''),
                data.get('新华财经-视频播出次数', ''),
                data.get('成员', ''),
                data.get('链接', ''),
                data.get('标题', '')
            ])
        
        # 转换数据用于计算得分
        scoring_data = convert_data_for_scoring(data)
        
        # 只有当平台字段有值时才计算分数
        if scoring_data.get('platform'):
            # 计算得分
            score = calculate_score(scoring_data)
            
            # 获取成员和部门信息
            member = data.get('成员', '')
            department = data.get('部门', '')
            
            # 保存得分信息
            save_score_to_csv(member, department, data.get('中稿媒体', ''), data.get('标题', ''), score, data.get('链接', ''))
            
            logger.info(f"计算得分: {score}，已保存到 {SCORE_CSV_FILE}")
            
            # 在响应中包含计算出的分数
            return jsonify({
                "status": "success", 
                "message": "Webhook received and data saved",
                "score": score
            }), 200
        else:
            return jsonify({
                "status": "success", 
                "message": "Webhook received and data saved, but no score calculated (missing platform)"
            }), 200
    
    except Exception as e:
        logger.error(f"Error processing webhook: {str(e)}")
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)